const util = require('../../utils/util.js');
const api = require('../../config/api.js');
const check = require('../../utils/check.js');
const rules = {
    payerName: '姓名',
    payerMobile: '联系方式',
    mail: "邮箱",
    payerUnit: "单位",
    typeNote: '年份',
    payerTypeName: "会员类型",
    postName: "姓名",
    postNumber: '手机号',
    postAddress: '地址',
    moneyStr: "实付"
}
Page({
    data: {
        payerUnit: '',
        payerName: "",
        types: ['普通会员30元/年', '高级会员100元/年'],
        payerType: '',
        payerTypeName: '',
        showTypePicker: false,
        typeNote: '',
        payerMobile: '',
        moneyStr: '',
        showYearPicker: false,
        years: [],
        year: '',
        isVoucher: "0",//报销凭证
        //  邮寄信息
        postNumber: '',
        postName: '',
        postAddress: '',
        postAddressError: "",
        postNameError: "",
        payerUnitError: "",
        payerMobileError: "",
        payerNameError: "",
        moneyStrError: "",
        payerTypeNameError: '',
        typeNoteError: '',
        postNumberError: ""
    },
    //电话校验格式
    phoneCheck(e) {
        let results = check.isValidPhone(e.detail)
        this.setData({
            payerMobileError: results
        })
    },
    onChange(e) {
        this.setData({
            isVoucher: e.detail,
            postNumber: '',
            postName: '',
            postAddress: '',
        })
    },
    onShareAppMessage() {
        return {};
    },
    view_5OnClick() {
        wx.navigateTo({url: '/pages/PayRecord/PayRecord'});
    },
    onConfirm(e) {
        this.setData({
            payerType: e.detail.index + 1,
            payerTypeName: e.detail.value,
            showTypePicker: false,
            moneyStr: e.detail.index == 0 ? 30 : 100,
            payerTypeNameError: ''
        })
    },
    onCancel() {
        this.setData({
            showTypePicker: false
        })
    },
    showTypePicker() {
        this.setData({
            showTypePicker: true,
        });
    },
    showYearPicker() {
        let array = []
        let currentYear = new Date().getFullYear()
        for (let i = currentYear - 2; i <= currentYear + 3; i++) {
            array.push(i)
        }
        this.setData({
            showYearPicker: true,
            years: array
        });
    },
    onConfirmYear(e) {
        this.setData({
            typeNote: e.detail.value,
            showYearPicker: false,
            typeNoteError: ''
        })
    },
    onCancelYear() {
        this.setData({
            showYearPicker: false
        })
    },
    onSubmit() {
        //邮寄信息
        const {
            payerUnit, payerName, typeNote, payerMobile, moneyStr, payerType
            , isVoucher, postNumber, postName, postAddress, payerTypeName
        } = this.data;
        let infoCreate = {
            payerUnit,
            payerName,
            typeNote,
            payerMobile,
            payerType,
            money: moneyStr * 100, payerTypeName
            , postNumber, postName, postAddress, isVoucher, moneyStr
        }
        let infoApply = {}
        if (isVoucher == '1') {
            infoApply = {
                payerUnit,
                payerName,
                typeNote,
                payerMobile,
                payerType,
                payerTypeName,
                postNumber,
                postName, postAddress,
                isVoucher
            }
        } else {
            infoApply = {
                payerUnit,
                payerName,
                typeNote,
                payerMobile,
                payerType,
                payerTypeName,
                isVoucher
            }
        }
        let hasError = false
        let keys = Object.keys(infoApply);
        for (let i = 0; i < keys.length; i++) {
            let message = this.validate(null, keys[i])
            if (message) {
                hasError = true;
            }
        }
        if (hasError) {
            wx.showToast({
                title: '字段填写不完整',
                icon: 'error',
                duration: 2000
            })
            return;
        }
        this.requestApi(infoCreate)
    },
    //校验，既要不为空，switch也要内容格式正确
    validate(e, objKey) {
        let {key} = (e && e.target.dataset) || {}
        let curKey = objKey || key;
        if (!rules.hasOwnProperty(curKey)) return ''
        let curVal = this.data[curKey];
        let message = '';
        if (!curVal) {
            this.setData({
                [curKey + 'Error']: rules[curKey] + '不可为空',
            })
            message = rules[curKey] + '不可为空';
        } else {
            this.setData({
                [curKey + 'Error']: '',
            })
            message = ''
        }
        switch (objKey) {
            case 'postNumber':
                message = check.isValidPhone(curVal)
                this.setData({
                    postNumberError: message
                })
                break;
            case 'mobile':
                message = check.isValidPhone(curVal)
                this.setData({
                    phoneError: message
                })
                break;
        }
        return message;
    },
    requestApi(infoApply) {
        util.request(api.FeePay, infoApply, 'post')
            .then(res => {
                if (res.errno === 200) {
                    const payParam = res.data;
                    wx.requestPayment({
                        'timeStamp': payParam.timeStamp,
                        'nonceStr': payParam.nonceStr,
                        'package': payParam.packageValue,
                        'signType': payParam.signType,
                        'paySign': payParam.paySign,
                        'success': function (res) {
                            wx.showModal({
                                title: '支付成功',
                                content: '',
                                showCancel: false,
                                success: function (res) {
                                    if (res.confirm) {
                                        wx.navigateBack({//返回
                                            delta: 1
                                        })
                                    }
                                }
                            })
                        },
                        'fail': function (res) {
                            console.log(res)
                            wx.showModal({
                                title: '支付失败：' + (res.errMsg === 'requestPayment:fail cancel'?'取消支付': res.errMsg),
                                content: '',
                                showCancel: false,
                            })
                        },
                        'complete': function (res) {
                        }
                    });
                } else {
                    wx.showToast({
                        title: res.errmsg,
                        icon: 'error',
                        duration: 2000
                    })
                }
            }).catch(e => {
        })
    }
});
